package com.example.demo.service;

import jakarta.persistence.EntityNotFoundException;
import com.example.demo.entity.Users;
import com.example.demo.repository.UserRepository;
import com.example.demo.security.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.UUID;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    public Optional<Users> login(String num, String password) {
        return userRepository.findByNum(num)
                .filter(user -> passwordEncoder.matches(password, user.getPassword()));
    }

    public String generateToken(String username) {
        return jwtTokenUtil.generateToken(username);
    }

    public Users register(Users user) {
        // 确保密码在注册时进行加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userRepository.save(user);
    }

    public Users update(Users user) {
        if (user.getId() == null) {
            // 如果 id 为空，则生成一个新的 UUID 作为 ID
            user.setId(UUID.randomUUID().toString());
        }
        Optional<Users> existingUser = userRepository.findByNum(user.getNum());
        if (existingUser.isPresent()) {
            // 更新现有记录的属性
            Users existing = existingUser.get();
            existing.setUsername(user.getUsername());
            existing.setAvatar_url(user.getAvatar_url());
            // 设置其他需要更新的字段...

            return userRepository.save(existing);
        } else {
            // 如果用户不存在，则保存新用户
            return userRepository.save(user);
        }
    }



}

